import elementResizeDetectorMaker from 'element-resize-detector'

export const addListener = () => {
  console.log('add-listener')
  let observer
  if (!window.$wujie) {
    observer = elementResizeDetectorMaker()
  } else {
    observer = {
      instance: new ResizeObserver((els) => {
        els.forEach((item) => {
          observer.targets.forEach((el, index) => {
            if (el.isEqualNode(item.target)) {
              observer.cbs[index]()
            }
          })
        })
      }),
      targets: [],
      cbs: [],
      listenTo: (target, cb) => {
        if (!target) return
        observer.instance.observe(target)
        observer.targets.push(target)
        observer.cbs.push(cb)
        cb()
      },
      uninstall: (target) => {
        if (!target) return
        observer.instance.unobserve(target)
        let index = observer.targets.findIndex((item) => item.isEqualNode(target))
        observer.cbs.splice(index, 1)
        observer.targets.splice(index, 1)
      },
    }
  }
  return observer
}
